package com.grm.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.grm.common.Result;
import com.grm.security.details.LoginUser;
import com.grm.sys.entity.SysRole;
import com.grm.sys.service.mapper.SysRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * security工具类
 *
 * @author gaorimao
 * @date 2022/02/10
 */
@Slf4j
@Component
public class SecurityUtils {
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 获取登录用户
     *
     * @return {@link LoginUser}
     */
    public LoginUser getLoginUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal == null){
            Result.renderJsonStr(response,Result.failed(500,"获取当前登录用户失败！"));
        }
        log.info("[principal] principal = {}", JSON.toJSONString(principal));
        return (LoginUser) principal;
    }

    /**
     * 判断用户是否是管理员
     *
     * @param userId 用户id
     * @return boolean
     */
    public boolean isAdmin(Long userId){
        boolean isAdmin = false;
        // 1.获取角色代码
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        String queryRoleIdsSql = "select role_id from sys_user_role where user_id = " + userId;
        sysRoleQueryWrapper.inSql("id", queryRoleIdsSql);
        List<SysRole> roles = sysRoleMapper.selectList(sysRoleQueryWrapper);
        for (SysRole sysRole : roles){
            if(sysRole.getCode().equals("admin")){
                isAdmin = true;
                break;
            }
        }
        return isAdmin;
    }
}
